<template>
  <el-dialog
    title="货位标签打印"
    :visible.sync="dialogVisible"
    width="90%"
    top="5vh"
    :close-on-click-modal="false"
    :append-to-body="true"
    @close="handleClose"
  >
    <div class="print-container">
      <!-- 左侧设置面板 -->
      <div class="settings-panel">
        <el-card shadow="never">
          <div slot="header">
            <span>打印设置</span>
          </div>
          
          <el-form :model="printSettings" label-width="100px" size="small">
            <el-form-item label="打印类型">
              <el-radio-group v-model="printSettings.type" @change="handleTypeChange">
                <el-radio label="qrcode">二维码</el-radio>
                <el-radio label="barcode">一维码</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="每行数量">
              <el-input-number
                v-model="printSettings.itemsPerRow"
                :min="1"
                :max="10"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="行间距(px)">
              <el-slider
                v-model="printSettings.rowSpacing"
                :min="0"
                :max="50"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="列间距(px)">
              <el-slider
                v-model="printSettings.columnSpacing"
                :min="0"
                :max="50"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="标签宽度(mm)">
              <el-input-number
                v-model="printSettings.labelWidth"
                :min="30"
                :max="150"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="标签高度(mm)">
              <el-input-number
                v-model="printSettings.labelHeight"
                :min="30"
                :max="150"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="字体大小">
              <el-input-number
                v-model="printSettings.fontSize"
                :min="10"
                :max="24"
                @change="updatePreview"
              />
            </el-form-item>
            
            <el-form-item label="显示内容">
              <el-checkbox-group v-model="printSettings.showFields" @change="updatePreview">
                <el-checkbox label="warehouseName">仓库名称</el-checkbox>
                <el-checkbox label="areaName">库区名称</el-checkbox>
                <el-checkbox label="locationCode">货位编码</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-divider />
            
            <div class="stats-info">
              <p>已选择: <strong>{{ selectedLocations.length }}</strong> 个货位</p>
              <p>预计页数: <strong>{{ estimatedPages }}</strong> 页</p>
            </div>
          </el-form>
        </el-card>
      </div>
      
      <!-- 右侧预览区域 -->
      <div class="preview-panel">
        <div class="preview-header">
          <h3>打印预览</h3>
          <div class="preview-actions">
            <el-button size="small" icon="el-icon-refresh" @click="updatePreview">刷新</el-button>
            <el-button size="small" icon="el-icon-zoom-in" @click="zoomIn">放大</el-button>
            <el-button size="small" icon="el-icon-zoom-out" @click="zoomOut">缩小</el-button>
          </div>
        </div>
        
        <div class="preview-content" :style="previewContentStyle">
          <div
            v-for="(page, pageIndex) in previewPages"
            :key="pageIndex"
            class="preview-page"
            :style="pageStyle"
          >
            <div
              v-for="(location, index) in page"
              :key="index"
              class="label-item"
              :style="labelItemStyle"
            >
              <!-- 二维码 -->
              <div v-if="printSettings.type === 'qrcode'" class="qrcode-container">
                <canvas :id="getQRCodeId(pageIndex, index)" :width="qrcodeSize" :height="qrcodeSize"></canvas>
              </div>
              
              <!-- 一维码 -->
              <div v-else class="barcode-container">
                <svg :id="getBarcodeId(pageIndex, index)"></svg>
              </div>
              
              <!-- 文字信息 -->
              <div class="label-text" :style="labelTextStyle">
                <p v-if="printSettings.showFields.includes('warehouseName')" class="text-line">
                  {{ location.stoName || '仓库名称' }}
                </p>
                <p v-if="printSettings.showFields.includes('areaName')" class="text-line">
                  库区: {{ location.stoAreaName || '库区名称' }}
                </p>
                <p v-if="printSettings.showFields.includes('locationCode')" class="text-line strong">
                  {{ location.stoUnitCode }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div slot="footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" icon="el-icon-printer" @click="handlePrint">打印</el-button>
    </div>
  </el-dialog>
</template>

<script>
import QRCode from 'qrcode';
import JsBarcode from 'jsbarcode';

export default {
  name: 'LocationPrintDialog',
  components: {},
  data() {
    return {
      dialogVisible: false,
      selectedLocations: [],
      printSettings: {
        type: 'qrcode',
        itemsPerRow: 4,
        rowSpacing: 15,
        columnSpacing: 15,
        labelWidth: 60,
        labelHeight: 80,
        fontSize: 12,
        showFields: ['warehouseName', 'areaName', 'locationCode']
      },
      previewPages: [],
      zoomLevel: 0.8
    };
  },
  computed: {
    qrcodeSize() {
      return Math.min(this.printSettings.labelWidth * 2.5, 150);
    },
    
    estimatedPages() {
      const itemsPerPage = this.printSettings.itemsPerRow * 8;
      return Math.ceil(this.selectedLocations.length / itemsPerPage);
    },
    
    pageStyle() {
      return {
        width: '210mm',
        minHeight: '297mm',
        padding: '10mm',
        background: 'white',
        marginBottom: '20px',
        boxShadow: '0 0 10px rgba(0,0,0,0.1)'
      };
    },
    
    labelItemStyle() {
      const widthPercent = 100 / this.printSettings.itemsPerRow;
      return {
        width: 'calc(' + widthPercent + '% - ' + this.printSettings.columnSpacing + 'px)',
        height: this.printSettings.labelHeight + 'mm',
        marginRight: this.printSettings.columnSpacing + 'px',
        marginBottom: this.printSettings.rowSpacing + 'px',
        padding: '8px',
        border: '1px solid #ddd',
        borderRadius: '4px',
        display: 'inline-flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        boxSizing: 'border-box',
        pageBreakInside: 'avoid'
      };
    },
    
    labelTextStyle() {
      return {
        fontSize: this.printSettings.fontSize + 'px'
      };
    },
    
    previewContentStyle() {
      return {
        transform: 'scale(' + this.zoomLevel + ')'
      };
    }
  },
  methods: {
    open(locations) {
      this.selectedLocations = locations || [];
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.updatePreview();
      });
    },
    
    handleClose() {
      this.dialogVisible = false;
      this.selectedLocations = [];
      this.previewPages = [];
      this.zoomLevel = 0.8;
      this.printSettings = {
        type: 'qrcode',
        itemsPerRow: 4,
        rowSpacing: 15,
        columnSpacing: 15,
        labelWidth: 60,
        labelHeight: 80,
        fontSize: 12,
        showFields: ['warehouseName', 'areaName', 'locationCode']
      };
    },
    
    handleTypeChange() {
      this.updatePreview();
    },
    
    updatePreview() {
      const itemsPerPage = this.printSettings.itemsPerRow * 8;
      this.previewPages = [];
      
      for (let i = 0; i < this.selectedLocations.length; i += itemsPerPage) {
        this.previewPages.push(this.selectedLocations.slice(i, i + itemsPerPage));
      }
      
      this.$nextTick(() => {
        if (this.printSettings.type === 'barcode') {
          this.renderBarcodes();
        } else {
          this.renderQRCodes();
        }
      });
    },
    
    renderQRCodes() {
      this.previewPages.forEach((page, pageIndex) => {
        page.forEach((location, index) => {
          const elementId = this.getQRCodeId(pageIndex, index);
          const canvas = document.getElementById(elementId);
          if (canvas) {
            const qrValue = this.getQRCodeValue(location);
            QRCode.toCanvas(canvas, qrValue, {
              width: this.qrcodeSize,
              margin: 1,
              errorCorrectionLevel: 'H'
            }).catch(error => {
              console.error('生成二维码失败:', error);
            });
          }
        });
      });
    },
    
    renderBarcodes() {
      this.previewPages.forEach((page, pageIndex) => {
        page.forEach((location, index) => {
          const elementId = this.getBarcodeId(pageIndex, index);
          const element = document.getElementById(elementId);
          if (element) {
            try {
              JsBarcode(element, location.stoUnitCode, {
                format: 'CODE128',
                width: 2,
                height: 60,
                displayValue: false,
                margin: 5
              });
            } catch (error) {
              console.error('生成条形码失败:', error);
            }
          }
        });
      });
    },
    
    getBarcodeId(pageIndex, index) {
      return 'barcode-' + pageIndex + '-' + index;
    },
    
    getQRCodeId(pageIndex, index) {
      return 'qrcode-' + pageIndex + '-' + index;
    },
    
    getQRCodeValue(location) {
      return JSON.stringify({
        warehouseId: location.stoId,
        areaId: location.stoAreaId,
        locationId: location.stoUnitId,
        locationCode: location.stoUnitCode,
        warehouseName: location.stoName,
        areaName: location.stoAreaName
      });
    },
    
    zoomIn() {
      if (this.zoomLevel < 1.5) {
        this.zoomLevel += 0.1;
      }
    },
    
    zoomOut() {
      if (this.zoomLevel > 0.5) {
        this.zoomLevel -= 0.1;
      }
    },
    
    handlePrint() {
      const printWindow = window.open('', '_blank');
      const printHtml = this.generatePrintHTML();
      
      printWindow.document.write(printHtml);
      printWindow.document.close();
      
      printWindow.onload = () => {
        if (this.printSettings.type === 'barcode') {
          this.renderBarcodesInPrintWindow(printWindow);
        } else {
          this.renderQRCodesInPrintWindow(printWindow);
        }
        
        setTimeout(() => {
          printWindow.print();
        }, 500);
      };
    },
    
    renderBarcodesInPrintWindow(printWindow) {
      this.previewPages.forEach((page, pageIndex) => {
        page.forEach((location, index) => {
          const elementId = this.getBarcodeId(pageIndex, index);
          const element = printWindow.document.getElementById(elementId);
          if (element) {
            JsBarcode(element, location.stoUnitCode, {
              format: 'CODE128',
              width: 2,
              height: 60,
              displayValue: false,
              margin: 5
            });
          }
        });
      });
    },
    
    renderQRCodesInPrintWindow(printWindow) {
      this.previewPages.forEach((page, pageIndex) => {
        page.forEach((location, index) => {
          const elementId = this.getQRCodeId(pageIndex, index);
          const canvas = printWindow.document.getElementById(elementId);
          if (canvas) {
            const qrValue = this.getQRCodeValue(location);
            QRCode.toCanvas(canvas, qrValue, {
              width: this.qrcodeSize,
              margin: 1,
              errorCorrectionLevel: 'H'
            });
          }
        });
      });
    },
    
    generatePrintHTML() {
      const s = this.printSettings;
      let html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>货位标签打印</title>';
      html += '<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"><\/script>';
      html += '<style>';
      html += '* { margin: 0; padding: 0; box-sizing: border-box; }';
      html += 'body { font-family: Arial, sans-serif; }';
      html += '.page { width: 210mm; min-height: 297mm; padding: 10mm; page-break-after: always; background: white; }';
      html += '.page:last-child { page-break-after: auto; }';
      html += '.label-item { width: calc(' + (100 / s.itemsPerRow) + '% - ' + s.columnSpacing + 'px); height: ' + s.labelHeight + 'mm; margin-right: ' + s.columnSpacing + 'px; margin-bottom: ' + s.rowSpacing + 'px; padding: 8px; border: 1px solid #ddd; border-radius: 4px; display: inline-flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; page-break-inside: avoid; vertical-align: top; }';
      html += '.qrcode-container, .barcode-container { margin-bottom: 8px; }';
      html += '.label-text { font-size: ' + s.fontSize + 'px; line-height: 1.4; }';
      html += '.text-line { margin: 2px 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }';
      html += '.strong { font-weight: bold; font-size: ' + (s.fontSize + 2) + 'px; }';
      html += '@media print { body { margin: 0; } .page { margin: 0; box-shadow: none; } }';
      html += '</style></head><body>';
      
      this.previewPages.forEach((page, pageIndex) => {
        html += '<div class="page">';
        page.forEach((location, index) => {
          html += '<div class="label-item">';
          
          if (s.type === 'qrcode') {
            const qrValue = this.getQRCodeValue(location);
            html += '<div class="qrcode-container"><canvas id="' + this.getQRCodeId(pageIndex, index) + '" width="' + this.qrcodeSize + '" height="' + this.qrcodeSize + '"></canvas></div>';
          } else {
            html += '<div class="barcode-container"><svg id="' + this.getBarcodeId(pageIndex, index) + '"></svg></div>';
          }
          
          html += '<div class="label-text">';
          if (s.showFields.includes('warehouseName')) {
            html += '<p class="text-line">' + (location.stoName || '仓库名称') + '</p>';
          }
          if (s.showFields.includes('areaName')) {
            html += '<p class="text-line">库区: ' + (location.stoAreaName || '库区名称') + '</p>';
          }
          if (s.showFields.includes('locationCode')) {
            html += '<p class="text-line strong">' + location.stoUnitCode + '</p>';
          }
          html += '</div></div>';
        });
        html += '</div>';
      });
      
      if (s.type === 'qrcode') {
        html += '<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.1/build/qrcode.min.js"><\/script><script>';
        this.previewPages.forEach((page, pageIndex) => {
          page.forEach((location, index) => {
            const qrValue = this.getQRCodeValue(location);
            html += 'QRCode.toCanvas(document.getElementById("qr-' + pageIndex + '-' + index + '"),"' + qrValue.replace(/"/g, '\\"') + '",{width:' + this.qrcodeSize + ',margin:1,errorCorrectionLevel:"H"});';
          });
        });
        html += '<\/script>';
      }
      
      html += '</body></html>';
      return html;
    }
  }
};
</script>

<style scoped lang="scss">
.print-container {
  display: flex;
  gap: 20px;
  height: 70vh;
}

.settings-panel {
  width: 300px;
  flex-shrink: 0;
  overflow-y: auto;
  
  .stats-info {
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
    
    p {
      margin: 5px 0;
      font-size: 14px;
      color: #606266;
      
      strong {
        color: #409EFF;
        font-size: 16px;
      }
    }
  }
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    
    h3 {
      margin: 0;
      font-size: 16px;
      color: #303133;
    }
    
    .preview-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .preview-content {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f5f7fa;
    transform-origin: top center;
    transition: transform 0.3s;
  }
}

.preview-page {
  background: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.label-item {
  background: white;
  
  .qrcode-container,
  .barcode-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .label-text {
    width: 100%;
    text-align: center;
    
    .text-line {
      margin: 2px 0;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .strong {
      font-weight: bold;
    }
  }
}
</style>
